﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.UI;
using shenghua.Commodity.Commodities;
using shenghua.Order.Orders.Median;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Member.Collection
{
    public class CollectionManager: DomainService
    {
        private readonly IRepository<CollectionCommodity> _collectionCommodityRepository;

        public CollectionManager(
            IRepository<CollectionCommodity> collectionCommodityRepository
            )
        {
            _collectionCommodityRepository = collectionCommodityRepository;
        }

        /// <summary>
        /// 收藏产品
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="commodityId"></param>
        /// <returns></returns>
        public async Task<CollectionCommodity> Add(Member.Members.Member member, CollectionCommodity collectionCommodity)
        {
            CollectionCommodity old =  _collectionCommodityRepository.GetAll().Where(r =>
                r.MemberId == member.Id &&
                r.CommodityId == collectionCommodity.CommodityId &&
                r.ShoppingOptionId == collectionCommodity.ShoppingOptionId).FirstOrDefault();

            if (old != null)
            {
                // 已经存在
                throw new UserFriendlyException("该产品已收藏");
            }

            // 不存在
            collectionCommodity.MemberId = member.Id;
            await _collectionCommodityRepository.InsertAsync(collectionCommodity);
            return collectionCommodity;
        }

        /// <summary>
        /// 获取用户所有收藏
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public async Task<List<CollectionCommodity>> GetAll(Member.Members.Member member)
        {
            var items = await _collectionCommodityRepository.GetAllListAsync(r => r.MemberId == member.Id);
            return items;
        }

        /// <summary>
        /// 删除一个收藏
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="collectionCommodityId"></param>
        /// <returns></returns>
        public async Task Remove(long memberId, int collectionCommodityId)
        {
            await _collectionCommodityRepository.DeleteAsync(r => r.MemberId == memberId && r.Id == collectionCommodityId);
        }

        public async Task Cancel(long memberId, int commodityId)
        {
            await _collectionCommodityRepository.DeleteAsync(r => r.MemberId == memberId && r.CommodityId == commodityId);
        }

        public async Task<bool> IsCollected(long memberId, int commodityId)
        {
            int count = _collectionCommodityRepository.GetAll().Where(r => r.MemberId == memberId && r.CommodityId == commodityId).Count();
            return count > 0;
        }
    }
}
